package com.wuseguang.springcloud.service.impl;

import com.wuseguang.springcloud.dao.jdbc.GroupJdbc;
import com.wuseguang.springcloud.dao.jdbc.StudentEvaluationScoreJdbc;
import com.wuseguang.springcloud.dao.repository.GroupRepository;
import com.wuseguang.springcloud.dao.repository.GroupStudentRepository;
import com.wuseguang.springcloud.entity.ClassGroup;
import com.wuseguang.springcloud.entity.GroupStudent;
import com.wuseguang.springcloud.service.GroupService;
import com.wuseguang.springcloud.util.Result;
import com.wuseguang.springcloud.util.UpdateTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 小组表 服务实现类
 * </p>
 *
 * @author 
 * @since 2020-02-07
 */
@Service
public class GroupServiceImpl implements GroupService {


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private GroupRepository groupRepository;
    @Autowired
    private GroupStudentRepository groupStudentRepository;
    @Autowired
    private GroupJdbc groupJdbc;
    @Autowired
    private StudentEvaluationScoreJdbc studentEvaluationScoreJdbc;


    @Override
    public Result findClassIdGroup(Integer classId, String teacherId,String termId) {

        logger.info("查询班级小组");
        //查询小组sql
        String sql = "select id,name,icon from `class_group` where class_id = ? and del = 0";
        List<Map<String,Object>> groupList = groupJdbc.queryListMap(sql,classId);
        Map<String,Object> returnMap = new HashMap<>();
        //查询教师的显示规则并且返回规则id
        String  id = studentEvaluationScoreJdbc.findTeacherRule(teacherId);
        //判断显示规则的i d
        if("1".equals(id)){
            returnMap.put("type",1);
            sql = "select sum(fraction) fractionSum  from student_evaluation_score_record where type = 2 and type_id =? " +
                    "   GROUP BY sign(fraction) ORDER BY fractionSum desc";
            for (Map<String,Object> map : groupList ) {

                try{
                    List<Map<String,Object>> list = studentEvaluationScoreJdbc.queryListMap(sql,map.get("id"));
                    if(list.isEmpty()){
                        //应为这个学生没有分数，所以要填写默认分数
                        Map<String,Object> map1 = new HashMap<>();
                        map1.put("fractionSum",0);
                        Map<String,Object> map2 = new HashMap<>();
                        map2.put("fractionSum",0);
                        list.add(map1);
                        list.add(map2);
                    }else if(list.size()==1){
                        //判断正负数
                        if(Integer.valueOf(list.get(0).get("fractionSum").toString())>0){
                            Map<String,Object> map2 = new HashMap<>();
                            map2.put("fractionSum",0);
                            list.add(map2);
                        }else{
                            //获取负分的分数
                            Integer  fractionSum =  Integer.valueOf(list.get(0).get("fractionSum").toString());
                            //重新创建
                            list = new ArrayList<>();
                            Map<String,Object> map1 = new HashMap<>();
                            map1.put("fractionSum",0);
                            Map<String,Object> map2 = new HashMap<>();
                            map2.put("fractionSum",fractionSum);
                            //赋值
                            list.add(map1);
                            list.add(map2);
                        }
                    }

                    map.put("list",list);

                    List stuList = getStuList(map.get("id").toString(),id,termId);
                    map.put("stuList",stuList);
                }catch (Exception e){
                    logger.info("没有分数");
                }
            }
        }else if ("2".equals(id)){
            sql = "select sum(fraction)  fraction  from student_evaluation_score_record where type = 2 and type_id =? ";
            for (Map<String,Object> map : groupList ) {

                try{
                    map.put("list",studentEvaluationScoreJdbc.queryListMap(sql,map.get("id")));
                    List stuList = getStuList(map.get("id").toString(),id,termId);
                    map.put("stuList",stuList);
                }catch (Exception e){
                    logger.info("没有分数");
                    map.put("list",new ArrayList<Map<String,Object>>(){
                        {
                            Map<String,Object> map2 =new HashMap<>();
                            map2.put("fractionSum",0);
                            add(map2);
                        }
                    });
                }

            }
            returnMap.put("type",2);
        }else{
            returnMap.put("type",3);

            for (Map<String,Object> map : groupList ) {
                List stuList = getStuList(map.get("id").toString(),id,termId);
                map.put("stuList",stuList);
            }
        }
        logger.info("数据大小 = {}",groupList.size());
        returnMap.put("stuList",groupList);
        return new Result(returnMap);
    }

    @Override
    public Result addClassIdGroup(ClassGroup classGroup) {

        logger.info("添加分组信息");

        try{
            //添加时间
           // classGroup.setCreationTime(new Date());
            classGroup.setDel(0);
            //组id
            Integer groupId =  groupRepository.save(classGroup).getId();
            //学生id
            Integer [] sutdentIds = classGroup.getStudentId();
            //循环学生id
            for (int i = 0 ;i<sutdentIds.length;i++){
                //创建组成员实体
                GroupStudent gs = new GroupStudent();
                gs.setGroupId(groupId);
                gs.setStudentId(sutdentIds[i]);
                //groupStudentRepository.deleteByStudentId(sutdentIds[i]);
                groupStudentRepository.save(gs);

            }

            return new Result();

        }catch (Exception e){
            e.printStackTrace();
            logger.error("添加失败",e);
            return new Result();
        }
    }

    @Override
    public Result deleteClassGroup(Integer id) {

        try {
            logger.info("解散小组信息");
            ClassGroup  group =  groupRepository.findById(id).get();
            group.setDel(1);
            groupRepository.save(group);
        } catch (Exception e) {

        }
        return new Result();
    }

    @Override
    public Result updateClassGroup(ClassGroup classGroup) {
        //获取程序
        ClassGroup classGroupTwo =  groupRepository.findById(classGroup.getId()).get();
        //创建修改工具
        UpdateTool.copyNullProperties(classGroupTwo, classGroup);
        groupRepository.save(classGroup);

        //先删除原来的成员
        groupStudentRepository.deleteByGroupId(classGroupTwo.getId());
        //学生id
        Integer [] sutdentIds = classGroup.getStudentId();
        //循环学生id
        for (int i = 0 ;i<sutdentIds.length;i++){
            //创建组成员实体
            GroupStudent gs = new GroupStudent();
            gs.setGroupId(classGroup.getId());
            gs.setStudentId(sutdentIds[i]);
            groupStudentRepository.deleteByStudentId(sutdentIds[i]);
            groupStudentRepository.save(gs);
        }
        return new Result();
    }


    public List<Map<String,Object>> getStuList(String groupId,String id,String termId){

        String sql = "select s.id,s.student_name,s.head_portrait headPortrait from  group_student gs left join student s on(gs.student_id=s.id) where group_id=? and s.id is not null";

        //每个班级的学生集合
        List<Map<String,Object>> stuList =  studentEvaluationScoreJdbc.queryListMap(sql,groupId);
        //判断显示规则的id
        if("1".equals(id)){

            //分数显示规则为加减分分开显示
             sql = "select sum(fraction) fractionSum  from student_evaluation_score " +
                    "where student_id = ? and term_id = ? GROUP BY sign(fraction) ORDER BY fractionSum desc";
            for (Map<String,Object> map :stuList) {
                try{
                    List<Map<String,Object>> list = studentEvaluationScoreJdbc.queryListMap(sql,map.get("id"),termId);
                    if(list.isEmpty()){
                        //应为这个学生没有分数，所以要填写默认分数
                        Map<String,Object> map1 = new HashMap<>();
                        map1.put("fractionSum",0);
                        Map<String,Object> map2 = new HashMap<>();
                        map2.put("fractionSum",0);
                        list.add(map1);
                        list.add(map2);
                    }else if(list.size()==1){
                        //判断正负数
                        if(Integer.valueOf(list.get(0).get("fractionSum").toString())>0){
                            Map<String,Object> map2 = new HashMap<>();
                            map2.put("fractionSum",0);
                            list.add(map2);
                        }else{
                            //获取负分的分数
                            Integer  fractionSum =  Integer.valueOf(list.get(0).get("fractionSum").toString());
                            //重新创建
                            list = new ArrayList<>();
                            Map<String,Object> map1 = new HashMap<>();
                            map1.put("fractionSum",0);
                            Map<String,Object> map2 = new HashMap<>();
                            map2.put("fractionSum",fractionSum);
                            //赋值
                            list.add(map1);
                            list.add(map2);
                        }
                    }

                    map.put("list",list);
                }catch (Exception e){
                    logger.info("没有分数");
                }
            }

        }else if("2".equals(id)){

            //分数显示规则为总分
            sql = "select sum(fraction)  fraction  from student_evaluation_score where student_id = ?  and term_id = ?" ;

            for (Map<String,Object> map :stuList) {

                try{
                    map.put("list",studentEvaluationScoreJdbc.queryListMap(sql,map.get("id"),termId));
                }catch (Exception e){
                    logger.info("没有分数");
                    map.put("list",new ArrayList<Map<String,Object>>(){
                        {
                            Map<String,Object> map2 =new HashMap<>();
                            map2.put("fractionSum",0);
                            add(map2);
                        }
                    });
                }
            }

        }
        return stuList;
    }
}
